package stream;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 流中元素去重
 */
public class StreamDistinct {
    public static void main(String[] args) {
        distinctNum();
        distinctStr();
        distinctObj();

    }

    private static void distinctObj() {
        Person p1 = new Person("张三", 18);
        Person p2 = new Person("李四", 19);
        Person p3 = new Person("张三", 19);
        Person p4 = new Person("张三", 18);
        List<Person> list = Arrays.asList(p1, p2, p3, p4);
        list.stream().distinct().forEach(System.out::println);
    }

    private static void distinctStr() {
        List<String> list = Arrays.asList("a", "b", "c", "a", "b");
        list.stream().distinct().forEach(System.out::println);
    }

    private static void distinctNum() {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2);
        list.stream().distinct().forEach(System.out::println);
    }
}

class Person {
    private String name;
    private Integer age;

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return name.equals(person.name) &&
                age.equals(person.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}